import json
import requests
import networkx as nx

url = "http://172.16.10.250:8080/nbzt-app-jcrh-zstp/platformManagement/importKnowledgeGraphByHttp"
Task_ID = "291"

def post_knowledge_graph(url, data, headers=None):
    try:
        # 发送POST请求
        response = requests.post(url, json=data, headers=headers)
        
        # 检查请求是否成功
        if response.status_code == 200:
            print("请求成功!")
            return response.json()  # 返回JSON格式的响应内容
        else:
            print(f"请求失败，状态码: {response.status_code}")
            return None
    except Exception as e:
        print(f"请求过程中发生错误: {e}")
        return None

# 定义函数将GraphML文件转换为本体JSON格式
def graphml_to_benti_json(graphml_file_path, output_json_file_path):
    # 读取GraphML文件
    graph = nx.read_graphml(graphml_file_path)
    
    # 创建输出的JSON数据结构
    graph_data = {
        "node": dict(),
        "relationship": []
    }
    
    entity_type_dict = dict()
    # 处理节点信息
    for node, attributes in graph.nodes(data=True):
        entity_type = attributes.get("entity_type", "unknown_type")
        attributes_new = {key: "" for key in attributes.keys() if key != "entity_type"}
        node_data = {
            entity_type: attributes_new
        }
        graph_data["node"].update(node_data)

        entity_type_dict[node] = entity_type
    
    # 处理边信息
    tmp_edge_set = set()
    for source, target, attributes in graph.edges(data=True):
        source_node = entity_type_dict.get(source, "unknown_type")
        target_node = entity_type_dict.get(target, "unknown_type")
        edge_keywords = attributes.get("keywords", "unknown_relation")
        if (source_node, target_node, edge_keywords) in tmp_edge_set:
            continue
        tmp_edge_set.add((source_node, target_node, edge_keywords))
        edge_data = {
            "起始节点": source_node,
            "目标节点": target_node,
            "关系名称": edge_keywords,
        }
        graph_data["relationship"].append(edge_data)
    
    # 将数据保存为JSON文件
    with open(output_json_file_path, 'w', encoding='utf-8') as f:
        json.dump(graph_data, f, ensure_ascii=False, indent=4)

    post_data = {
        "graphId": Task_ID,
        "type": 0, # 0表示本体，1表示实体
        "jsonString": json.dumps(graph_data, ensure_ascii=False)
        }
    post_knowledge_graph(url, post_data)

# 定义函数将GraphML文件转换为实体JSON格式
def graphml_to_shiti_json(graphml_file_path, output_json_file_path):
    # 读取GraphML文件
    graph = nx.read_graphml(graphml_file_path)
    
    # 创建输出的JSON数据结构
    graph_data = {
        "node": dict(),
        "relationship": []
    }
    
    # 处理节点信息
    for node, attributes in graph.nodes(data=True):
        entity_type = attributes.get("entity_type", "unknown_type")
        node_data = {
            node: attributes
        }
        if graph_data["node"].get(entity_type) is None:
            graph_data["node"][entity_type] = {node: attributes}
        else:
            graph_data["node"][entity_type][node] = attributes
    
    # 处理边信息
    for source, target, attributes in graph.edges(data=True):
        edge_data = {
            "起始节点": source,
            "目标节点": target,
            "关系名称": attributes.get("keywords", "unknown_relation"),
        }
        graph_data["relationship"].append(edge_data)
    
    # 将数据保存为JSON文件
    with open(output_json_file_path, 'w', encoding='utf-8') as f:
        json.dump(graph_data, f, ensure_ascii=False, indent=4)

    post_data = {
        "graphId": Task_ID,
        "type": 1, # 0表示本体，1表示实体
        "jsonString": json.dumps(graph_data, ensure_ascii=False)
        }
    post_knowledge_graph(url, post_data)

# 使用示例
graphml_file_path = 'graph_chunk_entity_relation.graphml'  # 替换为您的GraphML文件路径
graphml_file_path = 'graph_chunk_entity_relation_new.graphml'  # 替换为您的GraphML文件路径
output_json_file_path_benti = 'output_graph_benti_data_new.json'  # 输出的JSON文件路径
output_json_file_path_shiti = 'output_graph_shiti_data_new.json'  # 输出的JSON文件路径

# 转换文件
graphml_to_benti_json(graphml_file_path, output_json_file_path_benti)
graphml_to_shiti_json(graphml_file_path, output_json_file_path_shiti)

print(f"转换完成！结果保存在：{output_json_file_path_benti}")
print(f"转换完成！结果保存在：{output_json_file_path_shiti}")
